// Copyright (C) 2010  Joan Puigcerver Perez, <joapuipe@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#include <Person.hpp>

Person::Person(const Person_ID id)
  : Node(id)
{
}

Person_Name Person::name(mysqlpp::Connection* connection) const
{
  bool delete_connection = false;

  if ( connection == NULL ) {
    connection = db_create_and_connect(Config::get_DBName(), 
				       Config::get_DBHost(),
				       Config::get_DBUser(),
				       Config::get_DBPass());
    if ( connection == NULL ) return "";
    delete_connection = true;
  }
  
  mysqlpp::Query query = connection->query("SELECT per_name FROM persons\
 WHERE per_id = "+uint_to_str(_id)+";");
  mysqlpp::StoreQueryResult qres = query.store();
  if ( !qres ) {
    // error
    if ( delete_connection ) 
      db_disconnect_and_delete(&connection);
    return "";
  } 
  
  if ( delete_connection ) 
    db_disconnect_and_delete(&connection);
  return Person_Name(qres[0][0]);
}

std::list<Link> Person::links(mysqlpp::Connection* connection) const
{
  bool delete_connection = false;

  if ( connection == NULL ) {
    connection = db_create_and_connect(Config::get_DBName(), 
				       Config::get_DBHost(),
				       Config::get_DBUser(),
				       Config::get_DBPass());
    if ( connection == NULL ) return std::list<Link>();
    delete_connection = true;
  }
  
  mysqlpp::Query query = connection->query("SELECT mov_id, per_mov_role\
 FROM cast_mem WHERE per_id = "+uint_to_str(_id)+";");
  mysqlpp::StoreQueryResult qres = query.store();
  if ( !qres ) {
    // error
    if ( delete_connection ) 
      db_disconnect_and_delete(&connection);
    return std::list<Link>();
  } 
  
  if ( delete_connection ) 
    db_disconnect_and_delete(&connection);

  std::list<Link> links;
  for(size_t r = 0; r < qres.num_rows(); ++r) {
    links.push_back( Link(qres[r][0], _id, (std::string)qres[r][1]) );
  }

  return links;
}
